import fitz  # PyMuPDF
import io
import os
import os.path as osp
import sys
sys.path.append(osp.abspath(__file__).split('/tabel_and_images')[0])
import time
from PIL import Image, ImageDraw
import cv2
import cairosvg
import numpy as np
from bs4 import BeautifulSoup
import base64
threshold = 0.8
pdf_file = "1904.02701v1.pdf"
doc = fitz.open(pdf_file)
pdf_name = os.path.splitext(pdf_file)[0]
for i in range(len(doc)):
    # 使用PyMuPDF将PDF转为Pixmap，这相当于转为了位图
    pix = doc.get_page_pixmap(i)
    # 获取该页PDF上的文字内容
    text = doc.get_page_text(i)
    # 将Pixmap转为PIL Image对象
    mode = "RGBA" if pix.alpha else "RGB"    
    img_big = Image.frombytes(mode, [pix.width, pix.height], pix.samples)
    img_big = np.array(img_big, dtype=np.uint8)
    # images = doc.get_page_images(i)
    page = doc.load_page(i)
    svg_image = page.get_svg_image()
    soup = BeautifulSoup(svg_image, 'xml')
    image_tags = soup.find_all('image')
    for j, image in enumerate(image_tags):
        png_filename = f"1904.02701v1/page-svg-{i}-{j}.png"
        href = image.get('xlink:href').split(',')[-1].strip()
        base64_data = base64.b64decode(href)
        image = Image.open(io.BytesIO(base64_data))
        image.save(png_filename)
